<?php
namespace app\admin\controller;
use app\service\apiService;
use app\service\billService;
use app\service\communityService;
use app\service\roominfoService;
use app\service\roomUserService;
use app\service\xcxService;
use think\facade\Db;
use think\facade\View;
use think\facade\Log;

ini_set('max_execution_time','0');
class RoomUser extends Common{


   
    //显示小区房屋信息
    public function index(){
        //查询小区信息
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);//所有小区ID
        $whe[] = ['community_id','in',$com['community_id']];//所有小区ID
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);

		$str="[";
		foreach ($communitylist as $key => $value) {
			$str=$str."'".$value["community_name"]."',";
		}
		$str=$str."]";
		
		View::assign("str",$str);
        //查询
        $data = request()->get();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            View::assign('groups', array_values($groups));
                if (empty($data['group'])) {
                    $data['group'] = '';
                }       
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                sort($buildings);
                View::assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    sort($units);
                    View::assign('units',$units);
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        View::assign('rooms',$rooms);
                    }
                }
        }

        if (!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['room_id'])) {
                $where['room_id'] = $data['room_id'];//房屋编号
            }

            if(!empty($data['status'])){
                $where['status'] = $data['status'];//状态
            }else{
                $where['status'] = "";
            }
            View::assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where = null;
        }
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数
       
        $number =(new roomUserService())->userCount($community_id,$where);
        View::assign('number',$number);
        //查询房屋信息
        
        $roomlist = (new roomUserService())->userList($community_id,$page,$where);
        
        //判断是否有数据
        if(!empty($number)){
            foreach($roomlist as $room){
                
                //根据小区编号查询小区名称
                $room['community_id'] = (new roominfoService())->communityName($room['community_id']);
                //数据从新存入数组
                $list[] = $room;
                View::assign('list',$list);
            }
        }else{
            View::assign('list',$roomlist);
        }
        //View::assign('list',$roomlist);
        View::assign('roomlist',$roomlist);
       
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }


        return View::fetch('index');
    }





    public function userDelId(){
        $id=request()->get("id");

        $userinfo=Db::table("room_user")->where("id",$id)->find();
        if($userinfo["type"]==1){
            $user=Db::table("room_user")
                ->where("room_id",$userinfo["room_id"])
                ->where("type",2)
                ->find();
            if(!empty( $user)){
                return  json(['error' => '改用户是业主，请先删除改用户下的家人']);
            }
        }
        $result = (new roomUserService())->deleteUser($id);
        if($result){
            $this->success("删除用户成功");
        }else{
            $this->error("删除用户失败");
        }

    }

    //删除用户
    public function userDel(){
       
        $id = explode(',',request()->param('id'));
        $roomlist = (new roominfoService())->checkRoomInfo($id);
        if (count($roomlist) != count($id)) {
            return json(['error' => '房屋信息不存在']);
        }
        //查询房屋同步的状态
        $status=Db::table("roominfo")->where("id","in",$id)->distinct("status")->field("status")->select()->toArray();
        if(count($status)!="1"){
            return json(['error' => '请分别删除已同步未同步的房屋']);
        }
        $roomlist1=$roomlist;
        foreach($roomlist as $inf){
            //查询改房屋下是否有账单，如果有账单则需要先删除账单
            $billinfo=Db::table("bill")->where("out_room_id",$inf["out_room_id"])->find();
            if(!empty($billinfo)){
                return  json(['error' => '房屋删除失败,请先删除该房屋下的账单']); 
            }
        }
         //未同步的房屋删除
        foreach($roomlist as $inf){
            $result = (new roominfoService())->deleteRoomInfo($inf['id']);
            if(empty($result)){
                return json(['error' => '房屋删除失败']); 
            }
        }
        return json(['info' => '删除成功']);
        if($status[0]["status"]=="1"){
            //已同步的房屋删除
            
            //查询房屋是否属于同一小区
            $community=Db::table("roominfo")->where("id","in",$id)->distinct("community_id")->field("community_id")->select()->toArray();
            if(count($community)!="1"){
                return json(['error' => '房屋不是同一小区无法批量删除']);
            }
            $community_id=$community[0]["community_id"];
            $batch_id=date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号;
            $token = (new roominfoService())->communityToken($community_id);
            if($token){
                $api = new apiService(config('app')['delroom'], 'https://openapi.alipay.com/gateway.do');
                $res = $api->delRoom2(json_encode(['batch_id' => $batch_id, 'community_id' =>  $community_id, 'token' => $token]),json_encode($roomlist));
                if (!isset($res['error'])) {
                    foreach($roomlist as $inf){
                        $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                    }
                    return json(['info' => '删除成功']);
                }else{
                    return json(['error' => $res['error']]);
                }
            }else{
                return json(['error' => 'token获取失败']);
            }
            
        }else if($status[0]["status"]=="2"){
            //未同步的房屋删除
            foreach($roomlist as $inf){
                $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                if(empty($result)){
                    return json(['error' => '房屋删除失败']); 
                }
            }
            return json(['info' => '删除成功']);
        }else{
            return json(['error' => '房屋删除失败']);
        }
        
        
        //查询小区是否属于同一批次
        /*$batch=Db::table("roominfo")->where("id","in",$id)->distinct("batch_id")->field("batch_id")->select()->toArray();
        if(count($batch)!="1"){
            return json(['error' => '房屋不是同一批次无法批量同步']);
        }*/
       
    }


    
    //通过Excel批量添加房屋信息 


    
    public function getgroup(){
		$community_id = request()->param('community_id');
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = (new xcxService())->groupList($community_id);  
        
        sort($group ,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
    
        return $group ;
	}
    

}